package com.imooc.jdbc.servlet;

import com.imooc.jdbc.bean.Message;
import com.imooc.jdbc.service.MessageService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class MessageListServlet extends HttpServlet {

    private MessageService messageService;

    @Override
    public void init() throws ServletException {
        super.init();
        messageService = new MessageService();
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String pageStr = req.getParameter("page");
        int page = 1;
        if (null != pageStr && !("".equals(pageStr))) {
            try {
                page = Integer.parseInt(pageStr);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }

        int pageSize = 6;
        List<Message> messages = messageService.getMessages(page, pageSize);
        int count = messageService.countMessages();

        int last = count % pageSize == 0 ? (count / pageSize) : (count / pageSize + 1);
        req.setAttribute("last", last);
        req.setAttribute("messages", messages);
        req.setAttribute("page", page);
        req.getRequestDispatcher("/WEB-INF/views/biz/message_list.jsp").forward(req, resp);
    }

    @Override
    public void destroy() {
        super.destroy();
        messageService = null;
    }
}
